package com.century.sjt.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.EMChat.db.InviteMessgeDao;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.MainActivity;
import com.century.sjt.activity.Pay.CommodityActivity;
import com.century.sjt.activity.Pay.MerchantActivity;
import com.century.sjt.activity.Pay.MerchantItemActivity;
import com.century.sjt.activity.MyActivity;
import com.century.sjt.activity.NewsDetailActivity;
import com.century.sjt.activity.QRRecordCodeScanActivity;
import com.century.sjt.adapter.ActivityListViewAdapter;
import com.century.sjt.adapter.NewsListViewAdapter;
import com.century.sjt.adapter.ServiceListViewAdapter;
import com.century.sjt.domain.InviteMessage;
import com.century.sjt.entity.Banner;
import com.century.sjt.entity.Merchant;
import com.century.sjt.entity.ServiceData;
import com.century.sjt.util.Constant;
import com.century.sjt.util.ScrollViewListener;
import com.century.sjt.util.TipUtil;
import com.century.sjt.util.volleyUtil.LruImageCache;
import com.century.sjt.widget.ListViewForScrollView;
import com.century.sjt.widget.ObservableScrollView;
import com.century.sjt.widget.TitleBar.HomeTitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


public class FragmentHome extends BaseFragment {
    private Context mContext;
    private HomeTitleBar titleBar;

    //首页tab
    private LinearLayout mlltab1, mlltab2, mlltab3;
    private FrameLayout mlltab1_btn, mlltab2_btn, mlltab3_btn;
    private ListViewForScrollView listView1;
    private ListViewForScrollView listView2;
    private GridView gridView;
    //首页新闻、公司简介、最新活动的三个底部view
    private View vwTip1, vwTip2, vwTip3;
    private NewsListViewAdapter newsListViewAdapter;
    private ServiceListViewAdapter serviceListViewAdapter;
    private ActivityListViewAdapter activityListViewAdapter;
    private SimpleAdapter simp_adapter3;
    private List<Map<String, Object>> newsDatalist;
    private List<ServiceData> serviceDatalist;

    private List<Map<String, Object>> activityDatalist;
    //所有新闻按钮
    private Button loadAllNews;
    //所有新闻按钮
    private Button loadAllActivity;
    //tab2
//    private WebView webview2;
    private RequestQueue mQueue;
    private ObservableScrollView scMain;
//    private TextView tvMianTab2;
//    private ImageView ivMainTab2;

    //    topviewpager
    private ImageView[] imageViews = null;
    private ImageView imageView = null;
    private ViewPager advPager = null;
    private AtomicInteger what = new AtomicInteger(0);
    private boolean isContinue = true;
    private List<View> advPics;
    private List<Banner> mBannerDatalist;
    private TextView tvTip;
    private InviteMessgeDao inviteMessgeDao;

    private String typeTab = "1";//typeTab上拉更多时判断，1是新闻，3是活动
    private int currentPage1 = 1;
    private int currentPage2 = 1;
    private int currentPage3 = 1;
    private Handler mHandler;
    private boolean listView1IsOk = true;//判断上一次的请求是否完成
    private boolean listView2IsOk = true;//判断上一次的请求是否完成
    private boolean listView3IsOk = true;//判断上一次的请求是否完成
    private boolean isFirst = true;////判断是否第一次进入，或者刷新（下拉刷新是刷新所有的列表）
    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private String isShop,isMerchant;

    private ImageButton btnShop;

    public FragmentHome() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mQueue = Volley.newRequestQueue(getActivity());
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        activityListViewAdapter.notifyDataSetChanged();
                        serviceListViewAdapter.notifyDataSetChanged();
                        newsListViewAdapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isFirst = true;
                        newsDatalist.clear();
                        currentPage1 = 1;
                        serviceDatalist.clear();
                        currentPage2 = 1;
                        activityDatalist.clear();
                        currentPage3 = 1;
                        getActivityList();
                        break;
                    case 3:
                        //typeTab上拉更多时判断，1是新闻，3是活动
                        if (typeTab.equals("1")) {
                            currentPage1++;
                            getActivityList();
                        } else if (typeTab.equals("2")) {
                            currentPage2++;
                            getServiceList();

                        }else if (typeTab.equals("3")) {
                            currentPage3++;
                            getNewsList();

                        }
                        break;

                }
            }
        };
        initViews();
        initEvents();
        getBanner();

    }

    private void initEvents() {
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MyActivity.class);
                startActivity(intent);
            }
        });
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.setClass(getActivity(), QRRecordCodeScanActivity.class);
                intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent2, Constant.SCANNIN_GREQUEST_CODE);
            }
        });
        btnShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent3 = new Intent();
                intent3.setClass(getActivity(), MerchantActivity.class);
                intent3.putExtra("payType", "1");
                startActivity(intent3);
            }
        });
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout) getView().findViewById(R.id.activity_list_refesh);

        mlltab1_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //typeTab上拉更多时判断，1是新闻，3是活动
                typeTab = "1";
                mlltab1.setVisibility(View.VISIBLE);
                mlltab2.setVisibility(View.GONE);
                mlltab3.setVisibility(View.GONE);
                vwTip1.setBackgroundColor(getResources().getColor(R.color.textdefault_main));
                vwTip1.startAnimation(AnimationUtils.loadAnimation(getView().getContext(), R.anim.scale));
                vwTip2.setBackgroundColor(0x00000000);
                vwTip3.setBackgroundColor(0x00000000);
//                initTOP();
            }
        });

        mlltab2_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent3 = new Intent(Intent.ACTION_VIEW);
//                intent3.setData(Uri.parse("http://www.sjct518.com"));
//                startActivity(intent3);

                //typeTab上拉更多时判断，1是新闻，3是活动
                typeTab = "2";
                mlltab1.setVisibility(View.GONE);
                mlltab2.setVisibility(View.VISIBLE);
                mlltab3.setVisibility(View.GONE);
                vwTip2.setBackgroundColor(getResources().getColor(R.color.textdefault_main));
                vwTip2.startAnimation(AnimationUtils.loadAnimation(getView().getContext(), R.anim.scale));
                vwTip1.setBackgroundColor(0x00000000);
                vwTip3.setBackgroundColor(0x00000000);
            }
        });

        mlltab3_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //typeTab上拉更多时判断，1是新闻，3是活动
                typeTab = "3";
                mlltab1.setVisibility(View.GONE);
                mlltab2.setVisibility(View.GONE);
                mlltab3.setVisibility(View.VISIBLE);
                vwTip3.setBackgroundColor(getResources().getColor(R.color.textdefault_main));
                vwTip3.startAnimation(AnimationUtils.loadAnimation(getView().getContext(), R.anim.scale));
                vwTip1.setBackgroundColor(0x00000000);
                vwTip2.setBackgroundColor(0x00000000);
//                initTOP();
            }
        });


        listView1 = (ListViewForScrollView) getView().findViewById(R.id.lv_shouye_tab1);
        listView2 = (ListViewForScrollView) getView().findViewById(R.id.lv_shouye_tab2);
        gridView = (GridView) getView().findViewById(R.id.lv_shouye_tab3);
        newsDatalist = new ArrayList<Map<String, Object>>();
        //服务资讯修改
        serviceDatalist = new ArrayList<ServiceData>();
        activityDatalist = new ArrayList<Map<String, Object>>();
        newsListViewAdapter = new NewsListViewAdapter(getActivity(), mQueue, newsDatalist);
        serviceListViewAdapter = new ServiceListViewAdapter(getActivity(), mQueue, serviceDatalist,mHandler);
        activityListViewAdapter = new ActivityListViewAdapter(getActivity(), mQueue, activityDatalist);
        listView1.setAdapter(activityListViewAdapter);

        //服务资讯修改
        listView2.setAdapter(serviceListViewAdapter);

        gridView.setAdapter(newsListViewAdapter);

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                getActivity().overridePendingTransition(R.animator.in_from_right, R.animator.out_to_left);
                Map map = (Map) activityDatalist.get(position);
                SharedPreferences mainSharedPreferences = getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                isShop = mainSharedPreferences.getString("isShop", "");
                isMerchant = mainSharedPreferences.getString("isMerchant","");
                String shopId = (String) map.get("shopId");
                if ("1".equals(isMerchant)||"1".equals(isShop)){

                }else {

                }
                shopDetail(shopId);

            }
        });
        //修改
        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), CommodityActivity.class);
                intent.putExtra("url",  serviceDatalist.get(position).getUrl());
                intent.putExtra("type","service");
                startActivity(intent);
            }
        });




        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map map = (Map) newsDatalist.get(position);
                String sysid = (String) map.get("sysid");
                String title = (String)map.get("title");
                String image = (String)map.get("image");
                String createDate = (String)map.get("createDate");
                String url = (String)map.get("url");
                String content = (String)map.get("content");
                String newsType = (String)map.get("newsType");
                String summary = (String) map.get("summary");
                //Toast.makeText(SjtMainActivity.this, sysid, Toast.LENGTH_LONG).show();
//
                Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                intent.putExtra("sysid", sysid);
                intent.putExtra("url",url);
                intent.putExtra("image",image);
                intent.putExtra("title",title);
                intent.putExtra("summary",summary);
                startActivity(intent);
            }
        });

        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

        getActivityList();


    }
    @Override
    public void onDetach() {
        super.onDetach();

    }
    @Override
    public void onResume() {
        super.onResume();
        listView1.setFocusable(false);
        listView2.setFocusable(false);
        gridView.setFocusable(false);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String image = sharedPreferences.getString("image", "");
        titleBar.setLeftImageResource(getActivity(),Constant.ImageHost_Big + image);
//        webview2.setFocusable(false );

//        updateUnreadAddressLable();
//        getBanner();
    }

    /**
     * 保存提示新消息
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        // 提示有新消息
        SjtHelper.getInstance().getNotifier().viberateAndPlayTone(null);

        // 刷新bottom bar消息未读数
        updateUnreadAddressLable();
    }

    /**
     * 刷新申请与通知消息数
     */
    public void updateUnreadAddressLable() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
//					unreadAddressLable.setText(String.valueOf(count));
//                    tvTip.setVisibility(View.VISIBLE);
                } else {
//                    tvTip.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    /**
     * 获取未读申请与通知消息
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount();
        return unreadAddressCountTotal;
    }

    /**
     * 加载界面
     */
    private void initViews() {

        Typeface iconfont = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        titleBar = (HomeTitleBar) getView().findViewById(R.id.title_bar);
//        titleBar.setTitle(getResources().getString(R.string.text_home));
        titleBar.setRightIconResourc(getResources().getString(R.string.icon_scan_it));
        scMain = (ObservableScrollView) getView().findViewById(R.id.sv_main);
        tvTip = (TextView) getView().findViewById(R.id.tv_tip);
        btnShop = (ImageButton) getView().findViewById(R.id.btn_shopping);
        mlltab1_btn = (FrameLayout) getView().findViewById(R.id.lltab_1_top);
        mlltab2_btn = (FrameLayout) getView().findViewById(R.id.lltab_2_top);
        mlltab3_btn = (FrameLayout) getView().findViewById(R.id.lltab_3_top);
        mlltab1 = (LinearLayout) getView().findViewById(R.id.lltab_1);
        mlltab2 = (LinearLayout) getView().findViewById(R.id.lltab_2);
        mlltab3 = (LinearLayout) getView().findViewById(R.id.lltab_3);
        vwTip1 = getView().findViewById(R.id.vw_red_tip1);
        vwTip2 = getView().findViewById(R.id.vw_red_tip2);
        vwTip3 = getView().findViewById(R.id.vw_red_tip3);
        vwTip2.setBackgroundColor(0x00000000);
        vwTip3.setBackgroundColor(0x00000000);
        mBannerDatalist = new ArrayList<>();
        advPics = new ArrayList<View>();
        //--------------> Top 获取   <-----------------

        inviteMessgeDao = new InviteMessgeDao(getActivity());


        ScrollViewListener scrollViewListener = new ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                int scrollY = scrollView.getScrollY();
                float i = (float) scrollY;

//                滑动到底部刷新
                int height = scrollView.getHeight();
                int scrollViewMeasuredHeight = scMain.getChildAt(0).getMeasuredHeight();
                if ((scrollY + height) == scrollViewMeasuredHeight) {
                    //typeTab上拉更多时判断，1是新闻，3是活动
                    if (typeTab.equals("1")) {
                        //listView1IsOk判断上一次的请求是否完成
                        if (listView1IsOk) {
                            listView1IsOk = false;
                            Message msg = new Message();
                            msg.what = 3;
                            mHandler.sendMessage(msg);
                        }
                    }
                    if (typeTab.equals("2")) {
                        //listView1IsOk判断上一次的请求是否完成
                        if (listView2IsOk) {
                            listView2IsOk = false;
                            Message msg = new Message();
                            msg.what = 3;
                            mHandler.sendMessage(msg);
                        }
                    }
                    if (typeTab.equals("3")) {
                        if (listView3IsOk) {
                            listView3IsOk = false;
                            Message msg = new Message();
                            msg.what = 3;
                            mHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };



        scMain.setScrollViewListener(scrollViewListener);

        scMain.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        int height = view.getHeight();
                        int scrollY = view.getScrollY();
                        int scrollViewMeasuredHeight = scMain.getChildAt(0).getMeasuredHeight();
//                        if(scrollY==0){
//                            System.out.println("滑动到了顶端 view.getScrollY()="+scrollY);
//                        }
                        if ((scrollY + height) == scrollViewMeasuredHeight) {
                            System.out.println("滑动到了底部 scrollY=" + scrollY);
                            System.out.println("滑动到了底部 height=" + height);
                            System.out.println("滑动到了底部 scrollViewMeasuredHeight=" + scrollViewMeasuredHeight);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.qrRecordCodeResult(requestCode, resultCode, data);

    }

    //首页三个tab
    private void initTabs() {

    }

    private void getActivityList() {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        //--------------> 首页tab3 ListView <-----------------
        StringRequest stringRequestTabList1 = new StringRequest(Request.Method.POST,Constant.ShopActivityHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listView1IsOk = false;//判断上一次的请求是否完成
                try {
                    Log.e("sjt", "首页获取商家活动" + response.toString());
                    JSONTokener jsonTokener = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    JSONObject data = (JSONObject) res.getJSONObject("data");
                    String code = res.getString("code");
                    if (code.equals("407")){//异地登陆
                        TipUtil.showAppayRes(getActivity());
                    }else if (code.equals("200")) {
                        //Log.e("获取成功",response);
                        JSONArray activityList = data.getJSONArray("activityList");
                        if (activityList.length() == 0) {

                        } else {
                            for (int i = 0; i < activityList.length(); i++) {
                                JSONObject aactivity = (JSONObject) activityList.getJSONObject(i);
                                String title = aactivity.getString("title");//标题
                                String discount = aactivity.getString("discount");//折扣
                                String image = aactivity.getString("pictureId");
                                String shopId = aactivity.getString("shopId");
                                String shopName = aactivity .getString("shopName");
//                                Log.e("获取image", image);
                                //放入newsDatalist
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("pic", R.mipmap.aeebf4edbfc020);
                                map.put("text", title);
                                map.put("discount", discount);
                                map.put("image", image);
                                map.put("shopId", shopId);
                                map.put("shopName",shopName);
                                activityDatalist.add(map);
                            }
                            if(data.length()==Constant.PAGESIZE){//如果条数与请求的条数相同，可以继续上拉请求，否则就是已经没有数据了listView1IsOk = false不让他上拉操作了
                                listView1IsOk = true;
                            }
                        }
                    } else {
                        String message = res.getString("message");
                        Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.closeProgressDialog();

                if (isFirst) {//判断是否第一次进入，或者刷新（下拉刷新是刷新所有的列表）
//                    isFirst = false;
                    getServiceList();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listView1IsOk = true;//请求失败，可以执行下次请求
                currentPage1--;//请求如果失败，页数标志位回退
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.closeProgressDialog();
                Toast.makeText(getActivity(), getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("paging.currentPage", currentPage1+"");
                map.put("paging.pageSize", Constant.PAGESIZE +"");
                return map;


            }
        };
        mQueue.add(stringRequestTabList1);

    }



    private void getServiceList() {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        //--------------> 首页tab3 ListView <-----------------
        StringRequest stringRequestTabList1 = new StringRequest(Request.Method.POST,Constant.ServiceInfoHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listView1IsOk = false;//判断上一次的请求是否完成
                try {
                    Log.e("sjt", "首页获取服务咨询" + response.toString());
                    JSONTokener jsonTokener = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    String code = res.getString("code");
                    if (code.equals("200")) {

                        JSONObject data = res.getJSONObject("data");
                        if (data.length() == 0) {

                        } else {
                            JSONArray serviceInfoList = data.getJSONArray("serviceInfoList");
                            for (int i = 0; i < serviceInfoList.length(); i++) {
                                JSONObject item = (JSONObject) serviceInfoList.getJSONObject(i);
                                String content = item.getString("content");
                                String image = item.getString("image");
                                String url = item.getString("url");
                                String title = item.getString("title");
                                String shopId = item.getString("shopId");
                                String goodId = item.getString("goodId");
                                ServiceData serviceData = new ServiceData();
                                serviceData.setId(R.mipmap.aeebf4edbfc020);
                                serviceData.setContent(content);
                                serviceData.setGoodId(goodId);
                                serviceData.setShopId(shopId);
                                serviceData.setTitle(title);
                                serviceData.setUrl(url);
                                serviceData.setImage(image);
                                serviceData.setIsShow("0");
                                serviceDatalist.add(serviceData);
                            }
                            if(data.length()==Constant.PAGESIZE){//如果条数与请求的条数相同，可以继续上拉请求，否则就是已经没有数据了listView1IsOk = false不让他上拉操作了
                                listView2IsOk = true;
                            }
                        }
                    } else {
                        String message = res.getString("message");
                        Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.closeProgressDialog();

                if (isFirst) {//判断是否第一次进入，或者刷新（下拉刷新是刷新所有的列表）
                    isFirst = false;
                    getNewsList();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                listView2IsOk = true;//请求失败，可以执行下次请求
                currentPage2--;//请求如果失败，页数标志位回退
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.closeProgressDialog();
                Toast.makeText(getActivity(), getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("paging.currentPage", currentPage2+"");
                map.put("paging.pageSize", Constant.PAGESIZE +"");
                return map;
            }
        };
        mQueue.add(stringRequestTabList1);

    }

    private void getNewsList() {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        //--------------> 首页tab1 ListView <-----------------
        StringRequest stringRequestTabList1 = new StringRequest(Request.Method.POST, Constant.NewsHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listView3IsOk = false;
//                Log.e("sjt", "新闻数据：" + response);
                try {
                    JSONTokener jsonTokener = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    String code = res.getString("code");
                    if (code.equals("200")) {
                        //Log.e("获取成功", response);
                        JSONObject data = res.getJSONObject("data");
                        JSONArray newsList = data.getJSONArray("newsList");
                        if (newsList.length() == 0) {

                        } else {
                            for (int i = 0; i < newsList.length(); i++) {
                                JSONObject anew = (JSONObject) newsList.getJSONObject(i);
                                String title = anew.getString("title");
                                String sysid = anew.getString("sysId");
                                String image = anew.getString("image");
                                String createDate = anew.getString("createDate");
                                String url = anew.getString("url");
                                String content = anew.getString("content");
                                String newsType = anew.getString("newsType");
                                String summary = anew.getString("summary");

                                //Log.e("获取image",image);
                                //Log.e("获取title",title);
                                //放入newsDatalist
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("pic", R.mipmap.aeebf4edbfc020);
                                map.put("text", title);
                                map.put("sysid", sysid);
                                map.put("image", image);
                                map.put("createDate", createDate);
                                map.put("url",url);
                                map.put("content",content);
                                map.put("newsType",newsType);
                                map.put("title",title);
                                map.put("summary",summary);
                                newsDatalist.add(map);
                            }
                            if(newsList.length()==Constant.PAGESIZE){//如果条数与请求的条数相同，可以继续上拉请求，否则就是已经没有数据了listView3IsOk = false不让他上拉操作了
                                listView3IsOk = true;
                            }
                        }
                    } else {
                        String message = res.getString("message");
                        Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
//                    Log.e("111", e.getLocalizedMessage());
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);

                if (isFirst) {//判断是否第一次进入，或者刷新（下拉刷新是刷新所有的列表）
                    isFirst = false;
                    getService();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.closeProgressDialog();
                listView3IsOk = true;//请求失败，可以执行下次请求
                currentPage3--;//请求如果失败，页数标志位回退
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                Toast.makeText(getActivity(), getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("paging.currentPage", currentPage3 + "");
                map.put("paging.pageSize", Constant.PAGESIZE + "");
                return map;
            }
        };
        mQueue.add(stringRequestTabList1);

    }

    private void getService() {
        for (int i=0;i<5;i++) {
            ServiceData  serviceData=new ServiceData();
            serviceData.setId(R.mipmap.aeebf4edbfc020);
            serviceDatalist.add(serviceData);
        }

        Message msg = new Message();
        msg.what = 1;
        mHandler.sendMessage(msg);
    }

    /**
     * banner视图
     */
    //企业首页banner
    private void getBanner() {
        StringRequest stringRequestGetBanner = new StringRequest(Request.Method.POST, Constant.BannerListHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    //关闭进度条
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonTokener = new JSONTokener(response);
                    TipUtil.log("企业首页banner", response.toString(), 1);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    String message = res.getString("message");
                    String code = res.getString("code");
                    JSONObject data = res.getJSONObject("data");
                    if (code.equals("407")){//异地登陆
                        TipUtil.showAppayRes(getActivity());
                    }else if (code.equals("200")) {
                        //      这里存放的是四张广告背景


                        mBannerDatalist.clear();
                        advPics.clear();
                        JSONArray bannerlist = data.getJSONArray("banner");
                        for (int i = 0; i < bannerlist.length(); i++) {
                            JSONObject banner = (JSONObject) bannerlist.get(i);
                            String pictureId = banner.getString("pictureId");
                            String image = banner.getString("image");
                            final Banner sellBanner = new Banner();
                            sellBanner.setPictureId(pictureId);
                            sellBanner.setImage(image);
                            mBannerDatalist.add(sellBanner);
                            //图片加载
                            NetworkImageView img = new NetworkImageView(getActivity());
//                            ImageView img = new ImageView(getActivity());

                            img.setScaleType(ImageView.ScaleType.FIT_XY);
                            img.setScaleType(ImageView.ScaleType.FIT_XY);
                            img.setDefaultImageResId(R.mipmap.loginbg);
                            img.setErrorImageResId(R.mipmap.loginbg);
                            LruImageCache lruImageCache = LruImageCache.instance();
                            ImageLoader mImageLoader = new ImageLoader(mQueue, lruImageCache);
                            img.setImageUrl(Constant.BaseWebHost + image, mImageLoader);
//                            Glide.with(mContext).load(Constant.BaseWebHost + image).into(img);

//                            if (!"".equals(pictureId)) {
//                                FileUtil.setupBigImage(pictureId, mQueue, img);
//                            }
                            advPics.add(img);


                        }
                        initViewPager();
                    } else {
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (Exception e) {
                    //关闭进度条
                    TipUtil.closeProgressDialog();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                    TipUtil.log("企业首页banner", e + "", 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //关闭进度条
                TipUtil.closeProgressDialog();
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
            }
        })
//        {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                SharedPreferences sharedPreferences = MainActivity.mainSharedPreferences;
//                String token = sharedPreferences.getString("token", "");
//                Map<String, String> map = new HashMap<>();
//                map.put("token", token);
//                return map;
//            }
//        }
                ;

        mQueue.add(stringRequestGetBanner);
    }

    private void initViewPager() {

//        advPics = new ArrayList<View>();
        advPager = (ViewPager) getView().findViewById(R.id.adv_pager);
        ViewGroup group = (ViewGroup) getView().findViewById(R.id.viewGroup);


//
//        ImageView img1 = new ImageView(getActivity());
//        img1.setBackgroundResource(R.mipmap.shouyetupian);
//        img1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                Toast.makeText(getActivity(), "1", Toast.LENGTH_LONG).show();
//            }
//        });
//        advPics.add(img1);
////
//        ImageView img2 = new ImageView(getActivity());
//        img2.setBackgroundResource(R.mipmap.shouyetupian);
//        img2.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                Toast.makeText(getActivity(), "2", Toast.LENGTH_LONG).show();
//            }
//        });
//        advPics.add(img2);
////
//        ImageView img3 = new ImageView(getActivity());
//        img3.setBackgroundResource(R.mipmap.shouyetupian);
//        img3.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                Toast.makeText(getActivity(), "3", Toast.LENGTH_LONG).show();
//            }
//        });
//        advPics.add(img3);
//
//        ImageView img4 = new ImageView(getActivity());
//        img4.setBackgroundResource(R.mipmap.bg_banner_2);
//        img4.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Toast.makeText(getActivity(), "4", Toast.LENGTH_LONG).show();
//            }
//        });
//        advPics.add(img4);
//
//        ImageView img5 = new ImageView(getActivity());
//        img5.setBackgroundResource(R.mipmap.bg_banner_2);
//        img5.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Toast.makeText(getActivity(), "4", Toast.LENGTH_LONG).show();
//            }
//        });
//        advPics.add(img5);

//      对imageviews进行填充
        imageViews = new ImageView[advPics.size()];
//小图标
        for (int i = 0; i < advPics.size(); i++) {
            imageView = new ImageView(getActivity());
//            imageView.setLayoutParams(new ViewGroup.LayoutParams(20, 20));
//            imageView.setPadding(50, 50, 50, 50);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(20, 20);
            lp.setMargins(5, 5, 5, 5);
            imageView.setLayoutParams(lp);

            imageViews[i] = imageView;
            if (i == 0) {
                imageViews[i]
                        .setBackgroundResource(R.mipmap.icon_ellipsis1);
            } else {
                imageViews[i]
                        .setBackgroundResource(R.mipmap.icon_ellipsis2);
            }
            group.addView(imageViews[i]);
        }

        advPager.setAdapter(new AdvAdapter(advPics));
        advPager.setOnPageChangeListener(new GuidePageChangeListener());
        advPager.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                    case MotionEvent.ACTION_MOVE:
                        mSwipeLayout.setEnabled(false);
                        isContinue = false;
                        break;
                    case MotionEvent.ACTION_UP:
                        mSwipeLayout.setEnabled(true);
                        isContinue = true;
                        break;
                    default:
                        mSwipeLayout.setEnabled(true);
                        isContinue = true;
                        break;
                }
                return false;
            }
        });
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    if (isContinue) {
                        viewHandler.sendEmptyMessage(what.get());
                        whatOption();
                    }
                }
            }

        }).start();
    }

    private void whatOption() {
        what.incrementAndGet();
        if (what.get() > imageViews.length - 1) {
            what.getAndAdd(-(imageViews.length+1));
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {

        }
    }

    private final Handler viewHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            advPager.setCurrentItem(msg.what);
            super.handleMessage(msg);
        }

    };


    private final class GuidePageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int arg0) {
            what.getAndSet(arg0);
            for (int i = 0; i < imageViews.length; i++) {
                imageViews[arg0]
                        .setBackgroundResource(R.mipmap.icon_ellipsis1);
                if (arg0 != i) {
                    imageViews[i]
                            .setBackgroundResource(R.mipmap.icon_ellipsis2);
                }
            }

        }

    }

    private final class AdvAdapter extends PagerAdapter {
        private List<View> views = null;

        public AdvAdapter(List<View> views) {
            this.views = views;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(views.get(arg1));
        }

        @Override
        public void finishUpdate(View arg0) {

        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(views.get(arg1), 0);
            return views.get(arg1);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

    }

    private void shopDetail(final String shopId) {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ShopDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        Merchant merchant = new Merchant();
                        merchant.setShopId(aData.getString("shopId"));
                        merchant.setShopName(aData.getString("shopName"));
//                            Log.e("name",aData.getString("shopName"));
                        merchant.setLogo(aData.getString("logo"));
                        merchant.setDiscount(aData.getString("discount"));
                        merchant.setAddress(aData.getString("address"));
                        merchant.setTelephone(aData.getString("telephone"));
                        merchant.setTelephoneOne(aData.getString("telephoneOne"));
                        merchant.setMobile(aData.getString("mobile"));
                        merchant.setDesc(aData.getString("desc"));
                        merchant.setCity(aData.getString("city"));
                        merchant.setImage(aData.getString("image"));
                        merchant.setUserId(aData.getString("userId"));
                        merchant.setLastTopic(aData.getString("lastTopic"));
                        merchant.setNewGoods(aData.getString("newGoods"));
                        merchant.setLevel(aData.getInt("level"));
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), MerchantItemActivity.class);
                        Bundle mBundle = new Bundle();
                        mBundle.putSerializable("Merchant", merchant);
                        intent.putExtras(mBundle);
                        intent.putExtra("shopId", shopId);
                        intent.putExtra("payType","0");
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),getActivity(), 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId",shopId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


}
